package com.ruikong.dazhi.service.impl.baseinfo;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.dao.base.PersonnelMapper;
import com.ruikong.dazhi.dao.basicinfo.StockTypeMapper;
import com.ruikong.dazhi.entity.base.Personnel;
import com.ruikong.dazhi.entity.basicinfo.Stock;
import com.ruikong.dazhi.dao.basicinfo.StockMapper;
import com.ruikong.dazhi.entity.basicinfo.StockType;

import com.ruikong.dazhi.model.input.SearchMsgInput;
import com.ruikong.dazhi.model.input.StockPageInput;
import com.ruikong.dazhi.service.basicinfo.IStockService;
import com.ruikong.dazhi.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (Stock)表服务实现类
 *
 * @author HuaJiaYi
 * @since 2021-09-09 13:22:09
 */
@Service("stockService")
public class StockServiceImpl implements IStockService {
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private StockTypeMapper stockTypeMapper;
    @Autowired
    private PersonnelMapper personnelMapper;

    @Override
    public Stock queryById(Integer id) {
        return this.stockMapper.queryById(id);
    }

    @Override
    public int insert(Stock p) {
        p.setId(stockMapper.getId() + 1);
        return this.stockMapper.insert(p);
    }

    @Override
    public int update(Stock p) {
        return this.stockMapper.update(p);
    }

    @Override
    public int deleteById(Integer id) {
        return this.stockMapper.deleteById(id);
    }

    @Override
    public PageInfo<Stock> getStockPageList(StockPageInput input) {

        PageHelper.startPage(input.getPageNumber(), input.getPageSize());
        List<Stock> StockLists = this.stockMapper.getStockPageList(input);
        PageInfo<Stock> pageInfo = new PageInfo<>(StockLists);
        return pageInfo;
    }

    @Override
    public Integer isExist(Stock s) {
        return this.stockMapper.isExist(s);
    }

    //Excel
    @Override
    public BaseResult stockImport(MultipartFile multipartFile, Integer personnelId) {
        BaseResult baseResult = new BaseResult();
        //原料集合
        List<Stock> stockList = new ArrayList<>();
        try {
            //将multipartFileToFile转化为File
            File file = ExcelUtil.multipartFileToFile(multipartFile);
            InputStream inputStream = new FileInputStream(file);
            String fileName = file.getName();
            String suffix = fileName.split("\\.")[1];
            if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
                baseResult.setMsg("错误！提交文件格式不正确，请上传excel文件");
                baseResult.setCode(ResultApi.failCode);
                return baseResult;
            }
            //xlsx文件使用XSSFWorkbook，否则使用HSSFWorkbook
            Workbook workbook = suffix.equals("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Cell cell = null;
            Row row = null;
            Iterator<Row> iterator = sheet.rowIterator();
            int index = 0;
            while (iterator.hasNext()) {
                row = iterator.next();
                //跳过第一行标题行
                if (0 == index) {
                    index++;
                    continue;
                }
                //原料
                Stock stock = new Stock();
                //初始化原料——未删除
                stock.setIsDeleted(0);
                //原料编号
                cell = row.getCell(0);
                String stock_sn;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，原料编号不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    stock_sn = cell.getStringCellValue().trim();
                    if (stockMapper.isStockExist(stock_sn) > 0) {
                        baseResult.setMsg(String.format("错误！表格第%s行，原料编号已存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    } else {
                        stock.setStockSn(stock_sn);
                    }
                }
                //原料名称
                cell = row.getCell(1);
                String stock_name;
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，原料名称不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    stock_name = cell.getStringCellValue().trim();
                    stock.setStockName(stock_name);
                }
                // 英文名称
                cell = row.getCell(2);
                String stockNameEnglish;
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，英文名称不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    stockNameEnglish = cell.getStringCellValue().trim();
                    stock.setStockNameEnglish(stockNameEnglish);
                }
                //原料类型
                cell = row.getCell(3);
                String stock_type_name;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，原料类型不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    stock_type_name = cell.getStringCellValue().trim();
                    StockType stockType = this.stockTypeMapper.queryStockTypeByName(stock_type_name);
                    if (stockType == null) {
                        baseResult.setMsg(String.format("错误！表格第%s行，原料类型不存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    } else {
                        stock.setStockTypeId(stockType.getStockTypeId());
                    }
                }
                //计量单位
//                cell = row.getCell(4);
//                String measureunit;
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，计量单位不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
//                if (cell != null) {
//                    cell.setCellType(CellType.STRING);
//                    measureunit = cell.getStringCellValue().trim();
//                    stock.setMeasureunit(measureunit);
//                    if (measureunit == null) {
//                        baseResult.setMsg(String.format("错误！表格第%s行，计量单位不存在", index + 1));
//                        baseResult.setCode(ResultApi.failCode);
//                        file.delete();
//                        return baseResult;
//                    }
//                    else {
//                        stock.setMeasureunit(measureunit);
//                    }
//                }
                //规格型号
                cell = row.getCell(4);
                String model;
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，规格型号不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    model = cell.getStringCellValue().trim();
                    stock.setModel(model);
                }
                //每吨误差重量（kg）
//                cell = row.getCell(6);
//                Double error_number;
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，每吨误差重量（kg）不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
//                if (cell != null) {
//                    error_number = cell.getNumericCellValue();
//                    stock.setErrorNumber(error_number);
//                }
                //每吨误差重量（kg）
                cell = row.getCell(5);
                String storageCondition;
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，每吨误差重量（kg）不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    storageCondition = cell.getStringCellValue();
                    stock.setStorageCondition(storageCondition);
                }
                //制造商
                cell = row.getCell(6);
                String manufacturer;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    manufacturer = cell.getStringCellValue();
                    stock.setManufacturer(manufacturer);
                } else {
                    stock.setManufacturer("");
                }
                //供应商
                cell = row.getCell(7);
                String supplier;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    supplier = cell.getStringCellValue();
                    stock.setSupplier(supplier);
                } else {
                    stock.setSupplier("");
                }
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，供应商不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
//                if (cell != null) {
//                    cell.setCellType(CellType.STRING);
//                    supplier = cell.getStringCellValue().trim();
//                    if (supplier == null) {
//                        baseResult.setMsg(String.format("错误！表格第%s行，供应商不存在", index + 1));
//                        baseResult.setCode(ResultApi.failCode);
//                        file.delete();
//                        return baseResult;
//                    } else {
//                        stock.setSupplier(supplier);
//                    }
//                }
                //创建时间
                cell = row.getCell(8);
                Date createTime;
                if (cell != null) {
                    createTime = cell.getDateCellValue();
                    stock.setCreateTime(createTime);
                } else {
                    //创建时间不填
                    //以当前时间为准
                    stock.setCreateTime(new Date());
                }

//                //创建人
//                cell = row.getCell(8);
//                String personByName;
//                if (cell != null) {
//                    cell.setCellType(CellType.STRING);
//                    personByName = cell.getStringCellValue().trim();
//                    Personnel personnel = this.personnelMapper.queryPersonByName(personByName);
//                    if (personnel == null) {
//                        baseResult.setMsg(String.format("错误！表格第%s行，创建人不存在", index + 1));
//                        baseResult.setCode(ResultApi.failCode);
//                        file.delete();
//                        return baseResult;
//                    } else {
//                        stock.setUserId(personnel.getPersonnelId());
//                    }
//                } else {
//                    stock.setUserId(personnelId);
//                }

                //备注
                cell = row.getCell(9);
                String remarks;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    remarks = cell.getStringCellValue().trim();
                    stock.setRemarks(remarks);
                }

                //id
                if (stockMapper.getId() == null) {
                    stock.setId(1);
                } else {
                    stock.setId(stockMapper.getId() + 1);
                }
                //创建人
                stock.setUserId(personnelId);
                this.stockMapper.insert(stock);
//                stockList.add(stock);
                index++;
            }

//            baseResult = this.importSave(stockList);
            file.delete();
            baseResult.setMsg("导入成功");
        } catch (Exception e) {
            baseResult.setCode(ResultApi.errorCode);
            baseResult.setMsg("原料导入时出错");
            e.printStackTrace();
        }
        return baseResult;
    }

//    //导入信息保存
//    public BaseResult importSave(List<Stock> stockList) {
//        BaseResult baseResult = new BaseResult();
//        try {
//            for (int i = 0; i < stockList.size(); i++) {
//                Stock stockSave = stockList.get(i);
//                this.stockMapper.insert(stockSave);
//            }
//            baseResult.setMsg("导入成功");
//            baseResult.setCode(ResultApi.successCode);
//        } catch (Exception e) {
//            baseResult.setMsg("导入时出错");
//            baseResult.setCode(ResultApi.failCode);
//            e.printStackTrace();
//        }
//        return baseResult;
//    }
}
